const Controller = require('egg').Controller;

class OssController extends Controller {
    async upload() {
        const { ctx, service } = this;
        const stream = await ctx.getFileStream();

        if (!stream) {
            this.ctx.error(500, '未上传文件');
            return;
        }
        const filePath = `uploads/${Date.now()}-${stream.filename}`;
        try {
            const result = await service.oss.ali.upload(filePath, stream);
            this.ctx.success(result);
        } catch (error) {
            this.ctx.error(500, error.message);
        } finally {
            // 删除临时文件
            await ctx.cleanupRequestFiles();
        }
    }

    async get() {
        const { ctx, service } = this;
        const filePath = ctx.query.filePath;
        try {
            const result = await service.oss.get(filePath);
            this.ctx.success(result);
        } catch (error) {
            this.ctx.error(500, error.message);
        }
    }

    async delete() {
        const { ctx, service } = this;
        const filePath = ctx.query.filePath;
        try {
            const result = await service.oss.delete(filePath);
            this.ctx.success(result);
        } catch (error) {
            this.ctx.error(500, error.message);
        }
    }
}

module.exports = OssController;
